(function($){
if (typeof($.loaddata)=="undefined") {

	
	
	$.loaddata={};
	

	$.loaddata.fromFragment=function(d) {
		if (typeof d == "undefined") {
			d=document.location.href;
		}
		console.log("d="+d);
		d=d.match(/key=([^&\/]+)/);
		console.log("d="+d);

		return(d);
	}

 	$.loaddata.data={};
 	
 	$.loaddata.get=function(e) {
		var id=$(e).attr("id");
		var u=$(e).attr("href");
		var ol=$(e).attr("onload");
		if (typeof(ol)=="undefined") {
			ol="console.warn('spreadsheet ' + id + ' loaded, no onload code specified')";
		}
		var k;
		console.debug("found spreadsheet for a element id "+id+" "+u);
		if (u.indexOf('javascript:')==0) {
	    		k=(new Function("return "+u.substring('javascript:'.length)))();
	    		console.log("'"+u+"' found: "+k);
		} else {
	    		k=u.match(/key=([^&\/]+)/);
		}
		if (k) {
	    		console.debug("spreadsheet key: " +k[1]);
			var loadfunc;
			eval("loadfunc=function(a) { clearTimeout(jQuery.loaddata.data."+id+".timeout.list); jQuery.loaddata.loadlist('"+id+"',a)}"); 
			$.loaddata.data[id]={ 'key' : k[1], 'loadlist' : loadfunc, 'sheet' : [], 'parts' : 1, 'onload' : ol, 'timeout' : { 'list' : 0 } };
		$.loaddata.loadall(id);
		if (typeof($.loaddata[id])=="undefined") {
			$.loaddata[id]=$.loaddata.data[id];
			}
		}
 	}

	$.loaddata.loadall=function(id) {
       	var me=$.loaddata.data[id];
       	var u="http://spreadsheets.google.com/feeds/worksheets/"+me.key+"/public/basic?alt=json-in-script&callback=jQuery.loaddata.data."+id+".loadlist";
		$.loaddata.load(u,$.loaddata.data[id].timeout,"list");
	 }
	 

	$.loaddata.hasloaded=function(id) {
		var me=$.loaddata.data[id];
		var serr;
		try { eval("function(a){}") } catch (e) { serr=e };
		try {
			var ff=new Function("return("+me.onload+")");
			var ffe=ff();
			if (typeof ffe == "function") {
				ffe.apply(me,[me]);
			}
		} catch (e) {
			console.error("onload "+me.onload+" failed for "+id+": "+e);
		}
	}



 	$.loaddata.loadlist=function(id,a) {
	    var me=$.loaddata.data[id];
	    me.title=a.feed.title.$t;
		$(a.feed.entry).each(function(i,e) {
		  me.parts+=1;
		  var td="jQuery.loaddata.data."+id+".sheet["+me.sheet.length+"]";
		  var tios="jQuery.loaddata.data."+id+".timeout["+me.sheet.length+"]";
		  tioo=0;
		  var u=e.id.$t;
		  u=u.replace("/worksheets/","/list/");
		  u=u.replace(RegExp("/public/basic/(.*)"),"/$1/public/values?alt=json-in-script&callback="+td+".loader");
		  var loadfunc;
		  eval("loadfunc=function(a) { clearTimeout("+tios+"); "+td+".data=a; jQuery.loaddata.simplify("+td+","+"jQuery.loaddata.data."+id+");jQuery.loaddata.data."+id+".parts-=1; if (jQuery.loaddata.data."+id+".parts==0) { jQuery.loaddata.hasloaded('"+id+"');}  };");
		  var o={ loader: loadfunc, name : e.content.$t }
		  $.loaddata.load(u,$.loaddata.data[id].timeout,me.sheet.length);
		  me.sheet.push(o);
		});
		me.parts-=1;
		if (me.parts==0) {
			$.loaddata.hasloaded(id);
		}
	};
	
	$.loaddata.simplify=function(sheet,ws) {
		var r=[];
		$(sheet.data.feed.entry).each(function(i,e) {
	     var ds={}
		 for (a in e) { 
		     if (a.indexOf("gsx$")===0) {
		     	var k="";
		     	k=a.substr(4);
			ds[k]=e[a].$t;
			 } 	 
		 }
		 r.push(ds);
        });
		sheet.object=r;
		if (typeof(ws[sheet.name])=="undefined") {
			if (typeof($.loaddata.processors[sheet.name])!="undefined") {
				ws[sheet.name]=$.loaddata.processors[sheet.name](r);
			} else {
				ws[sheet.name]=r;
			}

		}
	}	

  $.loaddata.processors= {
		'settings' : function(r) {
			var ro={};
			$(r).each(function(i,o) {
				ro[o.name]=(new Function("return("+o.value+")"))();
			});
			return(ro);
		},
		'templates' : function(r) {
			if (typeof($.template)!="undefined") {
				var ro={};
				$(r).each(function(i,o) {
					ro[o.name]=$.template(o.name,o.template);
				});
				return(ro);
			} else {
				console.debug("Jquery Template Plugin https://github.com/jquery/jquery-tmpl not found, leaving template worksheet in peace");
				return(r);
			}
		}
}
  
   
  $.loaddata.load=function(u,o,a) {
   	var el=document.createElement("script");
       	el.setAttribute("src",u);
       	el.setAttribute("type","text/javascript");
       	document.getElementsByTagName("body")[0].appendChild(el);  
		if (typeof(o) != "undefined") {
			o[a]=window.setTimeout("var m='Data Error. Spreadsheet "+u+" did not load within 30 seconds';console.error(m)",30000);
			console.debug("set timeout #" + a+ " for "+u);
		}
   }   
   
  $.loaddata.init=function() {  
	$('a[rel=spreadsheet]').each(function(i,e) { $.loaddata.get(e) });
  }
 
 	
		if (typeof(console)==="undefined") {
			var console={ 'log' : function() {}, 'debug' : function() {}, 'error' : function() {} };
		}

  $(document).ready(function() {
  		$.loaddata.init();
  });


}
})(jQuery);
